package ru.voronoy.thefifteen.listeners;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import ru.voronoy.thefifteen.gui.MainWindow;

public class NameFrameListener implements ActionListener {

	private JFrame frame;
	private JTextField field;
	private String time;

	public NameFrameListener(JFrame frame, JTextField field, String time) {
		this.frame = frame;
		this.field = field;
		this.time = time;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		try {
			if (!field.getText().trim().equals("")) {
				DocumentBuilder builder = null;
				DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
				builder = f.newDocumentBuilder();
				Document doc = null;
				Element root = null;

				File file = new File("records.xml");

				if (!file.exists()) {
					file.createNewFile();
					doc = builder.newDocument();
					root = doc.createElement("root");
					doc.appendChild(root);
				} else {
					doc = builder.parse(file);
					root = doc.getDocumentElement();
				}

				Element playerName = doc.createElement("name");
				root.appendChild(playerName);
				Element gameResult = doc.createElement("result");
				root.appendChild(gameResult);

				playerName.appendChild(doc.createTextNode(field.getText()));
				gameResult.appendChild(doc.createTextNode(time));

				TransformerFactory tFactory = TransformerFactory.newInstance();
				Transformer transformer = tFactory.newTransformer();
				DOMSource source = new DOMSource(doc);
				StreamResult result = new StreamResult(file);
				transformer.transform(source, result);
				frame.setVisible(false);
				MainWindow.RecordsFrame();
			} else {
				JOptionPane.showMessageDialog(null,
						"Поле для ввода имени не может быть пустым!",
						"Внимание!", JOptionPane.WARNING_MESSAGE);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
